#include "Serial_port.h"
#include "main_windw.h"
#include "ui_main_windw.h"
#include "Down_load_process.h"
#include <QMessageBox>
#include <QDebug>
#include <qrandom.h>
#include <QFileInfo>
#include <QFile>
#include <QFileDevice>
#include <QDir>
#include <QDesktopServices>
#include <QDesktopServices>
#include <QUrl>
#include <QDateTime>
#include <QProcess>
#include "Timer.h"
#include <QJsonDocument>
#include <QJsonObject>

#include <QFileDialog>
#include <QSettings>
#include "data_filter/Usart1_Process.h"

uint8_t Main_windw::check_serial_state(void)
{

    int rand1 = 1;
    int rand2 = 1;
    QString strMsg = "请先打开串口再下载";
    QString color1 = "<font color=\"#FF";
    QString color2 = "\">";
    rand1 = qrand() % 10;
    rand2 = qrand() % 10;

    if (rand1 == 0)
    {
        rand1 = 1;
    }
    if (rand2 == 0)
    {
        rand2 = 1;
    }

    QString color3 = QString::number((rand1 * 10), 10);
    QString color4 = QString::number((rand2 * 10), 10);

    color1.append(color3).append(color4).append(color2);

    if (ui->open_serial_pushButton->text() == "关闭串口")
    {
        return 1;
    }
    else
    {
        //        ui->textBrowser_megtips->setText("请先打开串口再下载");
        ui->textBrowser_megtips->setText(color1 + strMsg + "</font> ");
        return 0;
    }
}
void Main_windw::show_user_msg(QString msg)
{

    int rand1 = 1;
    int rand2 = 1;

    QString color1 = "<font color=\"#FF";
    QString color2 = "\">";
    rand1 = qrand() % 10;
    rand2 = qrand() % 10;

    if (rand1 == 0)
    {
        rand1 = 1;
    }
    if (rand2 == 0)
    {
        rand2 = 1;
    }

    QString color3 = QString::number((rand1 * 10), 10);
    QString color4 = QString::number((rand2 * 10), 10);

    color1.append(color3).append(color4).append(color2);

    ui->textBrowser_megtips->setText(color1 + msg + "</font> ");
}

uint8_t hex_to_10(uint8_t hex)
{

    QString num = QString("%1").arg(hex, 0, 10);
    uint8_t dec = num.toUInt(nullptr, 16);
    dec = dec & 0xFF;
    //    qDebug()<<hex<<"year:"<<dec<<num<<endl;
    return dec;
}

void Main_windw::show_color_msg(QString strMsg)
{
    int rand1 = 1;
    int rand2 = 1;
    QString color1 = "<font color=\"#FF";
    QString color2 = "\">";
    rand1 = qrand() % 10;
    rand2 = qrand() % 10;

    if (rand1 == 0)
    {
        rand1 = 1;
    }
    if (rand2 == 0)
    {
        rand2 = 1;
    }

    QString color3 = QString::number((rand1 * 10), 10);
    QString color4 = QString::number((rand2 * 10), 10);

    color1.append(color3).append(color4).append(color2);

    ui->textBrowser_megtips->setText(color1 + strMsg + "</font> ");
}

QString pack_js_data(void)
{
    QJsonObject personObject; /*创建一个空的JSON对象*/
    /* 添加键值对到JSON对象*/
    personObject["type"] = 1;
    personObject["status"] = "online";
    QJsonDocument personDocument(personObject);         /* 创建一个JSON文档*/
    QByteArray jsonByteArray = personDocument.toJson(); /* 将JSON文档转换为字符串，方便输出或发送到网络*/
    QString jsonString(jsonByteArray);
    return jsonString;
}
/**
 * {type:"server",data:"base64"}
 */
void Main_windw::server_recv(QByteArray data)
{
    //    qDebug()<<"tcp recv:"<<data;

    Net_to_uart(data);

    // 将字符串转换为JSON文档
    //    QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8());

    //    QByteArray base64 = data.toUtf8().toBase64();

    //    // 检查转换是否成功
    //    if(!doc.isNull())
    //    {
    //        // 从文档中获取JSON对象
    //        QJsonObject jsonObject = doc.object();
    //        // 输出JSON对象的键值对
    //        // 查询键对应的值
    //        if (jsonObject.contains("type"))
    //        {
    //            if(jsonObject.contains("data")){
    //                QJsonValue Value = jsonObject["data"];
    //                if (Value.isString()){
    //                    QString data = Value.toString();
    //                    ui->textBrowser_net_recv->append(data);
    //                }
    //            }
    //        }else{
    //            // 输出整个JSON字符串
    //            QString jsonString = doc.toJson();
    //            qDebug() << jsonString;
    //        }
    //    }
}

void Main_windw::server_connect(QTcpSocket *clientSocket)
{

    QHostAddress clientIp = clientSocket->peerAddress();
    // 将IP地址转换为字符串
    QString clientIpString = clientIp.toString();

    qDebug() << "client connect:" << clientIpString;

    ui->lineEdit_tcp_client_ip->setText(clientIpString);
    ui->lineEdit_tcp_client_ip->setEnabled(false);
    ui->pushButton_connect_server->setEnabled(false);
    ui->label_tcpstateshow->setText("已连接");
    ui->textBrowser_megtips->setText("Tcp客户端已接入！");
    Net_connect_show_set(1);
}

void Main_windw::server_disconnect(QTcpSocket *clientSocket)
{

    Q_UNUSED(clientSocket);
    qDebug() << "client disconnect";
    ui->label_tcpstateshow->setText("未连接");
    ui->lineEdit_tcp_client_ip->setText(init_param.host_ip);
    ui->lineEdit_tcp_client_ip->setEnabled(true);
    ui->pushButton_connect_server->setEnabled(false);
    Net_connect_show_set(0);

    //    return;
    //    QHostAddress clientIp = clientSocket->peerAddress();
    //    // 将IP地址转换为字符串
    //    QString clientIpString = clientIp.toString();

    //    qDebug()<<"client connect:"<<clientIpString;
}

void Main_windw::client_recv(QByteArray data)
{
    //   qDebug()<<"client recv:"<<data;
    Net_to_uart(data);
}

void Main_windw::Net_connect_show_set(int state)
{
    if (state)
    {
        QPixmap pix = QPixmap(":/Src/net_connected.ico");
        ui->label_ico->setPixmap(pix);
    }
    else
    {
        QPixmap pix = QPixmap(":/Src/net_disconnect.ico");
        ui->label_ico->setPixmap(pix);
    }
}

void Main_windw::client_connect(QTcpSocket *ServerSocket)
{
    Q_UNUSED(ServerSocket);
    ui->lineEdit_tcp_client_ip->setEnabled(false);
    ui->pushButton_connect_server->setEnabled(false);
    ui->label_tcpstateshow->setText("已连接");
    ui->textBrowser_megtips->setText("Tcp客户端已连接！");
    Net_connect_show_set(1);
    qDebug() << "client conect:" << endl;
}

void Main_windw::client_disconnect(QTcpSocket *ServerSocket)
{
    Q_UNUSED(ServerSocket);
    ui->lineEdit_tcp_client_ip->setEnabled(true);
    ui->pushButton_connect_server->setEnabled(true);
    ui->label_tcpstateshow->setText("未连接");
    Net_connect_show_set(0);
    qDebug() << "client disconnect:" << endl;
}

void Main_windw::on_pushButton_connect_server_clicked()
{
    QString server_ip = ui->lineEdit_tcp_client_ip->text();
    if (!server_ip.isEmpty())
    {
        if (client)
        {
            if (client->state() != QTcpSocket::UnconnectedState)
            {
                client->disconnectFromHost();
            }
            client->Set_server_info(server_ip);

            ui->textBrowser_megtips->setText("客户端连接中...");

            QMessageBox msgBox(this);
            msgBox.setWindowTitle("连接中...");
            msgBox.setModal(true);
            msgBox.show();

            if (client->Connect_server())
            {
                ui->textBrowser_megtips->setText("客户端连接失败");
                msgBox.setText("连接失败");
                msgBox.exec();
            }
            else
            {
                msgBox.close();
            }

            init_param.host_ip = server_ip;
            set_sys_params(init_param);
            qDebug() << "client conect click:" << server_ip;
        }
        else
        {
            show_my_tips("提示！", "请选择一个Tcp模式！", false);
        }
    }
}

void Main_windw::on_checkBox_mode_client_clicked(bool checked)
{
    // 取消勾选
    if (checked == false)
    {
        ui->checkBox_mode_client->setEnabled(true);
        ui->checkBox_mode_server->setEnabled(true);
        Close_client();
        Net_connect_show_set(0);
        ui->textBrowser_megtips->setText("Tcp客户端已断开！");
    }
    else
    {
        ui->checkBox_mode_client->setEnabled(true);
        ui->checkBox_mode_server->setEnabled(false);
        Open_client();
        init_param.run_mode = E_RUN_MODE_CLIENT;
        ui->textBrowser_megtips->setText("Tcp客户端已启用！");
    }
}

void Main_windw::on_checkBox_mode_server_clicked(bool checked)
{
    // 取消勾选
    if (checked == false)
    {
        ui->checkBox_mode_client->setEnabled(true);
        ui->checkBox_mode_server->setEnabled(true);
        server_disconnect(NULL);
        Close_server();
        ui->textBrowser_megtips->setText("Tcp服务器已关闭！");
    }
    else
    {
        ui->checkBox_mode_client->setEnabled(false);
        ui->checkBox_mode_server->setEnabled(true);
        Open_server();
        init_param.run_mode = E_RUN_MODE_SERVER;
        ui->textBrowser_megtips->setText("Tcp服务器已开启！");
    }
}

void Main_windw::Load_sys_params(void)
{

    QSettings settings("params.ini", QSettings::IniFormat);
    init_param.run_mode = (e_run_mode_t)settings.value("run_mode").toInt();
    init_param.host_ip = settings.value("host_ip").toString();
    init_param.hex_mode = settings.value("hex_mode").toInt();
    init_param.Filter_log_enable = settings.value("Filter_log").toInt();

    if (init_param.run_mode == E_RUN_MODE_NULL)
    {
        ui->checkBox_mode_client->setEnabled(true);
        ui->checkBox_mode_client->setCheckState(Qt::Checked);
        ui->checkBox_mode_server->setEnabled(false);
        ui->checkBox_mode_server->setCheckState(Qt::Unchecked);
        init_param.run_mode = E_RUN_MODE_CLIENT;
    }
    else if (init_param.run_mode == E_RUN_MODE_CLIENT)
    {
        ui->checkBox_mode_client->setEnabled(true);
        ui->checkBox_mode_client->setCheckState(Qt::Checked);
        ui->checkBox_mode_server->setEnabled(false);
        ui->checkBox_mode_server->setCheckState(Qt::Unchecked);
        init_param.run_mode = E_RUN_MODE_CLIENT;
    }
    else if (init_param.run_mode == E_RUN_MODE_SERVER)
    {
        ui->checkBox_mode_client->setEnabled(false);
        ui->checkBox_mode_client->setCheckState(Qt::Unchecked);
        ui->checkBox_mode_server->setEnabled(true);
        ui->checkBox_mode_server->setCheckState(Qt::Checked);
        init_param.run_mode = E_RUN_MODE_SERVER;
    }

    if (init_param.host_ip.isEmpty())
    {
        init_param.host_ip = "192.168.1.1";
    }

    if (init_param.hex_mode == 1)
    {
        ui->checkBox_hex_mode->setCheckState(Qt::Checked);
    }
    else
    {
        ui->checkBox_ascii_mode->setCheckState(Qt::Checked);
    }

    if (init_param.hex_mode_recv == 1)
    {
        ui->checkBox_hex_recv->setCheckState(Qt::Checked);
    }
    else
    {
        ui->checkBox_ascii_recv->setCheckState(Qt::Checked);
    }

    if (init_param.Filter_log_enable == 1)
    {
        ui->checkBox_filter_log->setCheckState(Qt::Checked);
    }
    else
    {
        ui->checkBox_filter_log->setCheckState(Qt::Unchecked);
    }

    ui->lineEdit_tcp_client_ip->setText(init_param.host_ip);

    qDebug() << "load run mode:" << init_param.run_mode << "ip:" << init_param.host_ip;
}

void Main_windw::set_sys_params(s_init_param_t init_param)
{

    QSettings settings("params.ini", QSettings::IniFormat);
    qDebug() << "save run_mode:" << init_param.run_mode;
    settings.setValue("run_mode", init_param.run_mode);
    settings.setValue("host_ip", init_param.host_ip);
    settings.setValue("hex_mode", init_param.hex_mode);
    settings.setValue("hex_mode_recv", init_param.hex_mode_recv);
    settings.setValue("Filter_log", init_param.Filter_log_enable);
}

void Main_windw::on_pushButton_clicked()
{
    ui->textBrowser_net_recv->clear();
}

void Main_windw::on_pushButton_2_clicked()
{
    ui->textBrowser_net_send->clear();
}

void Main_windw::on_checkBox_hex_mode_clicked(bool checked)
{
    if (checked)
    {
        init_param.hex_mode = 1;
        ui->checkBox_ascii_mode->setCheckState(Qt::Unchecked);
    }
}

void Main_windw::on_checkBox_ascii_mode_clicked(bool checked)
{
    if (checked)
    {
        init_param.hex_mode = 2;
        ui->checkBox_hex_mode->setCheckState(Qt::Unchecked);
    }
}

void Main_windw::on_checkBox_hex_recv_clicked(bool checked)
{
    if (checked)
    {
        init_param.hex_mode_recv = 1;
        ui->checkBox_ascii_recv->setCheckState(Qt::Unchecked);
        qDebug() << checked;
    }
}

void Main_windw::on_checkBox_ascii_recv_clicked(bool checked)
{
    if (checked)
    {
        init_param.hex_mode_recv = 2;
        ui->checkBox_hex_recv->setCheckState(Qt::Unchecked);
        qDebug() << checked;
    }
}
void Main_windw::filter_show_close_cb(void)
{
    Filtershow = nullptr;
    ui->checkBox_filter_show->setCheckState(Qt::Unchecked);
    qDebug() << "close";
}
/**
 * 打开协议字段显示窗口
 */
void Main_windw::on_checkBox_filter_show_clicked(bool checked)
{
    if (checked)
    {
        filter_show_start();
    }
    else
    {
        if (Filtershow)
        {
            Filtershow->close();
            destroyed(Filtershow);
            Filtershow = nullptr;
        }
    }
}

void Qstring_to_hex_data(QString str, uint8_t *buf)
{
    uint16_t num = 0;
    // 字符串转换为hex
    for (int i = 0; i < str.size(); i += 2)
    {
        num = str.mid(i, 2).toUInt(nullptr, 16);
        buf[i / 2] = num & 0xFF;

        qDebug() << buf[i / 2];

        if (buf[i / 2] == 0)
        {
            qDebug() << "Err_hex:";
        }
    }
}

/**
 * 协议头部过滤
 */
void Main_windw::on_lineEdit_protocol_head_editingFinished()
{
    uint8_t buf[16] = {0};
    QString str = ui->lineEdit_protocol_head->text().toUtf8();

    /*判断是否为空并且必须是2的倍数*/
    if (str.isEmpty() || (str.length() % 2 != 0))
    {
        return;
    }
    Qstring_to_hex_data(str, buf);

    set_pack_head(buf[0]);
}

/**
 * 协议尾部过滤
 */
void Main_windw::on_lineEdit_protocol_tail_editingFinished()
{
    uint8_t buf[16] = {0};
    QString str = ui->lineEdit_protocol_tail->text().toUtf8();
    if (str.isEmpty() || (str.length() % 2 != 0))
    {
        return;
    }
    Qstring_to_hex_data(str, buf);

    set_pack_tail(buf[0]);
}

/**
 * 启用数据过滤
 */
void Main_windw::on_checkBox_filter_log_clicked(bool checked)
{
    if (checked)
    {
        init_param.Filter_log_enable = 1;
    }
    else
    {
        init_param.Filter_log_enable = 0;
    }
}
